﻿using JiaBao.Core;
using JiaBao.Services.CustomerService;
using JiaBao.Services.ExcelService;
using JiaBao.Services.LogService;
using System;
using System.Data;
using System.IO;
using System.Windows;
using System.Windows.Controls;

namespace JiaBao.WPF.Customer
{
    /// <summary>
    /// p_Customer_Birthday.xaml 的交互逻辑
    /// </summary>
    public partial class p_Customer_Birthday : Page
    {
        private readonly ICustomerService _customerService;
        private readonly IExcelService _excelService;

        public p_Customer_Birthday(ICustomerService customerService,IExcelService excelService )
        {
            InitializeComponent();
            this._customerService = customerService;
            this._excelService = excelService;
            dp_End.BlackoutDates.AddDatesInPast();
            dp_End.SelectedDate = DateTime.Now.AddDays(7);
            dp_End.DisplayDate  = DateTime.Now.AddDays(7);
        }

        private void btn_Select_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var dt = _customerService.GetByBirthday(DateTime.Now, (DateTime )dp_End.SelectedDate );
                if (null == dt)
                    MessageBox.Show("日期选择错误");
                SetDataGrid(dt);
            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }
        }

        private void SetDataGrid(DataTable dt)
        {
            dg_Main.ItemsSource = dt.DefaultView;

        }

        private void btn_ToExcel_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var p = CommonHelper.FolderBrowserDialog();

                if (null == p) return;

                p = Path.Combine(p, "近期生日" + DateTime.Now.ToString("yyyy-MM-dd") + "-"+ ((DateTime)dp_End.SelectedDate).ToString ("yyyy-MM-dd") +".xls");


                if (null == dg_Main.ItemsSource) return;
                var dt = (dg_Main.ItemsSource as DataView).ToTable();
                if (0 == dt.Rows.Count) return;

                byte[] excel = _excelService.DataTableToExcel(dt);


                if (!File.Exists(p))
                {
                    FileStream fs = new FileStream(p, FileMode.CreateNew);
                    fs.Write(excel, 0, excel.Length);
                    fs.Close();

                }
                MessageBox.Show("导出完成");
            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }
        }
    }
}
